var time =2000
//时间转换
function renderTime(date) {
    var dateee = new Date(date).toJSON();
    return new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
}
//获取token数据
function postDataplain(url, data) {
    return fetch(process.env.VUE_APP_URL + url, {
        body: data,
        headers: {
            "content-type": "text/plain"
        },
        method: 'POST',
    })
        .then(response => {
            if (response.status === 200) {
                return response.json();
            } else {
                thrownewError("服务器无法连接");
            }
        })
}
//不带token
function postDatajson(url, data) {
    return fetch(process.env.VUE_APP_URL + url, {
        body: data,
        headers: {
            "content-type": "application/json",
        },
        method: 'POST',
    })
        .then(response => {
            if (response.status === 200) {
                return response.json();
            } else if (response.status === 404) {
                return response.status
            } else if (response.status === 500) {
                return response.status
            }
        })
}
//带token
function postData(url, data, token) {
    var tokens = "Bearer " + token
    return fetch(process.env.VUE_APP_URL + url, {
        body: data,
        headers: {
            "content-type": "application/json",
            "Authorization": tokens
        },
        method: 'POST',
    })
        .then(response => {
            if (response.status === 200) {
                return response.json();
            } else {
                thrownewError("服务器无法连接");
            }
        })
}
//登录token
function Loading() {
    postDatajson("/api/TokenAuth/Authenticate", JSON.stringify({ userNameOrEmailAddress: "admin", password: "123qwe", rememberClient: true }))
        .then(function (response) {
            sessionStorage.setItem("token", response.result.accessToken)
        })
        .catch((error) => {

        });
}
function ceshi() {
    console.log("123123");
}
//登录
function Loadings(selfs) {
    const self = selfs;
    let Error = 0
    postDatajson(
        "/api/TokenAuth/Authenticate",
        JSON.stringify({
            userNameOrEmailAddress: self.username,
            password: self.password,
            rememberClient: true,
            TenantName:"HengHong",
        })
    ).then(function (response) {
        if (response === 404) {
            self.Error="服务器无法连接"
        }else if(response === 500){
            self.Error="账号或密码错误"
        }
        else {
            sessionStorage.setItem("token", response.result.accessToken);
            postData("/api/User/GetByUserName", JSON.stringify({ "UserName": self.username }), response.result.accessToken).
                then(function (user) {
                sessionStorage.setItem("userid", user.result.result.id)
                //角色
                sessionStorage.setItem("role", user.result.result.role)
                //学校ID
                sessionStorage.setItem("schoolId", user.result.result.schoolId)
                //用户名ID
                 sessionStorage.setItem("UserName", user.result.result.name)
                //性
                sessionStorage.setItem("Surname", user.result.result.Surname)
                sessionStorage.setItem("productId", 11)
                sessionStorage.setItem("ProductActivationListArr",1)
                sessionStorage.setItem("ProductInventoryArr",1)
                self.$router.push({
                    name: 'Home',
                });
            }).catch(error => {
                 alert("没有该用户的账号信息")
            });
        }
    }).catch((error) => {
        
    });
    
}
//获取教师所有班级
//创建班级(通过字符串)
function CreateClass(selfs) {

}
//获取班级（教师）
function GetTeacherClassAll(selfs) {
    postData("/api/CourseManage/GetCourse", JSON.stringify({ creatorId: sessionStorage.getItem("userid"), "ProductId": 11 }), sessionStorage.getItem("token"))
        .then(function (response) {
            // console.log(response)
            selfs.$emit("handleChange", response.result.result.courseGroup);
        })
        .catch((error) => {
        });
}
//表单验证
function isClass(rule, value, callback) {
    if (!value) {
        return callback(new Error('输入不可以为空'));
    }
    var pattern = /^[\u4e00-\u9fa5a-zA-Z-z0-9]+$/im
    if (pattern.test(value)) {
        return callback()
    }
    return callback(new Error('只能输入数字,汉字,字母'))
}
function isTimeClass(rule, value, callback) {
    let times =/^(\d{4})(-)(\d{2})$/
    if (times.test(value)) {
        return callback();
      }
      return callback(new Error('请输入正确的时间格式:XXXX(年)-XX(月)'))
  }
function Identity(rule, value, callback){
    let  identity  =  /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/
    if (identity.test(value)) {
        return callback();
      }
      return callback(new Error('请输入正确的身份证号'))
}
function NumberVerification(rule, value, callback){
    let  number  =  /^\d+$|^\d+[.]?\d+$/
    if (number.test(value)) {
        return callback();
      }
      return callback(new Error('只能输入数字'))
}
function CharacterVerification(rule, value, callback){
    let  Character = /[^\u4E00-\u9FA5]/g
    if (!Character.test(value)) {
        return callback();
      }
      return callback(new Error('只能输入汉字'))
}
function IponeVerification(rule, value, callback){
    let  Ipone = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    if (Ipone.test(value)) {
        return callback();
      }
      return callback(new Error('请输入正确的手机号'))
}

//转换时间1
function TimeChange(number) {
    var integers = parseInt(number / 60)
    var yu = number % 60
    var strings = ''
    if (integers == 0) {
        strings = yu + "秒"
    } else {
        strings = integers + "分" + yu + "秒"
    }
    return strings
}
function TimeChangeTwo(number) {
    var fen = parseInt(number / 60)
    var miao = number % 60
    var shi = 0
    var yufen = 0
    if (fen > 60) {
        shi = parseInt(fen / 60)
        if (shi < 10) {
            shi = "0" + shi
        }
    }
    yufen = fen % 60
    if (yufen < 10) {
        yufen = "0" + yufen
    }
    if (miao < 10) {
        miao = "0" + miao
    }
    return shi + ":" + yufen + ":" + miao
}
//设置cookie
function setCookie(c_name, c_pwd, exdays, checked) {
    var exdate = new Date(); //获取时间
    exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
    //字符串拼接cookie
    window.document.cookie = "userName" + "=" + c_name + ";path=/;expires=" + exdate.toGMTString();
    window.document.cookie = "userPwd" + "=" + c_pwd + ";path=/;expires=" + exdate.toGMTString();
}
//读取cookie
function getCookie() {
    let arrs = []
    if (document.cookie.length > 0) {
        var arr = document.cookie.split('; ');
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].split('=')[0] === 'userName') {
                arrs.push(arr[i].split('=')[1])
            }
            if (arr[i].split('=')[0] === 'userPwd') {
                arrs.push(arr[i].split('=')[1])
            }
        }
    }
    return arrs
}
//清除cookie
function clearCookie() {
    setCookie("", "", -1); //修改2值都为空，天数为负1天就好了
}
//计算两个时间只差
// TimeDifference ('2020-09-10 17:10:29','2020-9-18 17:11:35');
function TimeDifference(time1, time2) {
    //定义两个变量time1,time2分别保存开始和结束时间
    var stime = new Date(time1).getTime();
    var etime = new Date(time2).getTime();
    var usedTime = (etime - stime) / 1000;  //两个时间戳相差的毫秒数
    // var days=Math.floor(usedTime/(24*3600*1000));
    //              //计算出小时数
    // var leave1=usedTime%(24*3600*1000);    //计算天数后剩余的毫秒数
    // var hours=Math.floor(leave1/(3600*1000));
    //              //计算相差分钟数
    // var leave2=leave1%(3600*1000);        //计算小时数后剩余的毫秒数
    // var minutes=Math.floor(leave2/(60*1000));
    // var time = days + "天"+hours+"时"+minutes+"分";
    //var time = days;
    return TimeChange(usedTime)
}
//new Date转化成时间格式
function dateToFormat(value) {
    const dateTme = new Date(value)
    const Y = dateTme.getFullYear()
    const M = dateTme.getMonth() + 1 < 10 ? "0" + (dateTme.getMonth() + 1) : dateTme.getMonth() + 1
    const D = dateTme.getDate() < 10 ? "0" + dateTme.getDate() : dateTme.getDate()
    const h = dateTme.getHours() < 10 ? "0" + dateTme.getHours() : dateTme.getHours()
    const m = dateTme.getMinutes() < 10 ? "0" + dateTme.getMinutes() : dateTme.getMinutes()
    const s = dateTme.getSeconds() < 10 ? "0" + dateTme.getSeconds() : dateTme.getSeconds()
    return Y + "-" + M + "-" + D + " " + h + ":" + m + ":" + s
}
function fortime(time1, time2) {
    var t1 = dateFormats(time1)
    var t2 = dateToFormat(time2)
    var stime = new Date(t1).getTime();
    var etime = new Date(t2).getTime();
    var usedTime = (etime - stime) / 1000;
    return usedTime

}
function dateFormats(dataStr) {
    var dateee = new Date(dataStr).toJSON();
    return new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
}
function deepClone(source) {
    const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象
    for (const keys in source) { // 遍历目标
        if (source.hasOwnProperty(keys)) {
            if (source[keys] && typeof source[keys] === 'object') { // 如果值是对象，就递归一下
                targetObj[keys] = source[keys].constructor === Array ? [] : {};
                targetObj[keys] = deepClone(source[keys]);
            } else { // 如果不是，就直接赋值
                targetObj[keys] = source[keys];
            }
        }
    }
    return targetObj;
}
function ObjectToString(Arr){
    let obj = {}
    for (let item in Arr){
      obj[Arr[item].name] = Arr[item].value;
    };
    return obj
}

export { time,postDataplain, postDatajson, postData, Loadings, CreateClass, GetTeacherClassAll, renderTime, isClass, TimeChange, setCookie, getCookie, clearCookie, TimeDifference, TimeChangeTwo, dateToFormat, fortime,deepClone,ObjectToString,isTimeClass,Identity,NumberVerification,CharacterVerification,IponeVerification}